package com.lgx.mall.core.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lgx.common.entity.Dictionary;
import com.lgx.common.exception.DataException;
import com.lgx.common.web.Constants;
import com.lgx.common.web.Pagination;
import com.lgx.common.web.json.Json2Utils;
import com.lgx.common.web.util.DictUtils;
import com.lgx.common.web.util.EscapeUtils;
import com.lgx.right.entity.User;
import com.lgx.right.service.IUserService;
import com.lgx.right.util.PasswordUtils;
/**
 * 处理会员
 * @author ZhangChao
 *
 */

@Controller
@RequestMapping("/member")
public class MemberController {

	@Autowired
	private IUserService userService;

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	
	//首页跳转用户管理页面
	@RequestMapping("/memberMgr.do")
	public String munberMgr(HttpServletRequest request,HttpServletResponse response){
		return "mall/member/memberMgr";
	}
	
	//打开管理页面需要加载的数据
	@RequestMapping("/list.do")
	public void list(HttpServletRequest request,HttpServletResponse response){
		String name = request.getParameter("name");
		String mobile = request.getParameter("mobile");
		String card  = request.getParameter("card");
		String registerTimeStar = request.getParameter("registerTimeStar");
		String registerTimeEnd = request.getParameter("registerTimeEnd");
		String cardStart = request.getParameter("cardStart");  
		
		String pageNum = request.getParameter("page");
		String pageSize= request.getParameter("rows");
		
		if(StringUtils.isEmpty(pageSize))pageSize = Constants.PAGE_SIZE;
		if(StringUtils.isEmpty(pageNum))pageNum = Constants.FIRST_PAGE_NUM;
		
		User user = (User) request.getSession().getAttribute(Constants.LOGIN_USER);   //自动抓取当前用户的信息
		if(user != null){
			//四个空字段分别为会员管理中使用到得，在user里面作为一个空字符串传递即可
			Pagination page = this.userService.findUserList("1",user.getOrgId(), user.getUserType(),name,mobile, card,registerTimeStar,registerTimeEnd,cardStart,"", Integer.parseInt(pageSize), Integer.parseInt(pageNum));
		    Json2Utils.parseJSON(page, response);
		}
	}
	
	@RequestMapping("/init.do")
	public String init(HttpServletRequest request,HttpServletResponse response){
		String userId = request.getParameter("userId");
		String type = request.getParameter("type");
		
		if("edit".equals(type)){//如果操作状态为编辑，则把勾选的用户信息作为一个对象传送
			User user = this.userService.findUserById(Long.parseLong(userId));   //根据这个id查找到用户
			request.setAttribute("user", user);
		}
		
		//性别级联
		List<Dictionary> sexTypes = DictUtils.getDictListByKind(DictUtils.SEX_TYPE);
		request.setAttribute("sexTypes", sexTypes);
		
		//传入必要的操作类型和操作id
		request.setAttribute("type", type);
		request.setAttribute("userId", userId);
		
		User onlineUser = (User)request.getSession().getAttribute(Constants.LOGIN_USER);
		request.setAttribute("onlineUser", onlineUser);
		
		return "mall/member/member-init";
	}
	
	/**
	 * 处理修改或者是添加
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/save.do")
	@ResponseBody
	public String save(HttpServletRequest request,HttpServletResponse response){
		String cardId = request.getParameter("cardid");               //接受卡号
		if(!StringUtils.isEmpty(cardId))cardId = EscapeUtils.unescape(cardId);
		
		String truename = request.getParameter("truename").trim();    //接受用户真实名
		if(!StringUtils.isEmpty(truename))truename = EscapeUtils.unescape(truename);
		
		Integer sex = Integer.parseInt(request.getParameter("sex").trim());  //1 --  先生   0 --  小姐
		
		String username = request.getParameter("username").trim();     //接受用户登录名
		if(!StringUtils.isEmpty(username))username = EscapeUtils.unescape(username);
		
		String email = request.getParameter("email").trim();          //接受邮件
		if(!StringUtils.isEmpty(email))email = EscapeUtils.unescape(email);
		
		String mobile = request.getParameter("mobile").trim();         //接受用户手机
		if(!StringUtils.isEmpty(mobile))mobile = EscapeUtils.unescape(mobile);
		
		String orgId = request.getParameter("orgId").trim();
		String orgName = request.getParameter("orgName").trim();
		if(!StringUtils.isEmpty(mobile))orgName = EscapeUtils.unescape(orgName);
		String orgType = request.getParameter("orgType").trim();
		
		
		
		//用户添加人，即当前登陆用户/操作用户的信息
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER); 
		
		//创建自动密码
		String password = PasswordUtils.passwordRandom();
				
		//新添加用户的信息
		User user = new User();
		System.out.println(password);
		
		//将数据存入user实体
		user.setSex(sex);               //用户性别 
		user.setUsername(username);     //登陆名
		user.setTruename(truename);     //真实姓名
		user.setPassword(password);
		user.setUserType(1);            //用户类型,为1表示是普通会员
		user.setEmail(email);           //用户邮箱
		user.setMobile(mobile);         //用户电话
		user.setLastLogin(new Date());
		user.setCreateName(onlineUser.getUsername());   //创建人信息
		user.setCreateId(onlineUser.getId());           //创建人信息
		user.setRegisterTime(new Date());
		user.setIsDelete("0");
		user.setParent(onlineUser.getId());
		user.setParentType(onlineUser.getUserType());
		user.setLocked(false);
		
		user.setOrgId(Long.parseLong(orgId));
		user.setOrgName(orgName);
		user.setOrgType(orgType);
		
		//调用后台
		//cardId为手动输入的卡号,如果cardId为空，系统将会附加默认卡号
		 try {
			user = userService.createUser(user,cardId);
		} catch (DataException e) {
			e.printStackTrace();
			return "0";
		}
		
		return "1";
	} 
	
	
	//修改实现
	@RequestMapping("/update.do")
	@ResponseBody
	public String update(HttpServletRequest request,HttpServletResponse response){
		String userId = request.getParameter("userId");
		
		String truename = request.getParameter("truename").trim();
		if(!StringUtils.isEmpty(truename))truename = EscapeUtils.unescape(truename);
		
		Integer sex = Integer.parseInt(request.getParameter("sex").trim());  //1 --  先生   0 --  小姐
		
		String email = request.getParameter("email").trim();
		if(!StringUtils.isEmpty(email))email = EscapeUtils.unescape(email);
		
		User user = this.userService.findUserById(Long.parseLong(userId));
		//将数据存入user实体
		user.setTruename(truename);     //用户真实姓名
		user.setSex(sex);               //用户性别 
		user.setEmail(email);           //用户邮箱
		
		//调用后台
		 try {
			user = userService.updateUser(user);
		} catch (DataException e) {
			e.printStackTrace();
			return "0";
		}
		return "1";
	}
	
	
	@RequestMapping("/delete.do")
	@ResponseBody
	public String delete(HttpServletRequest request,HttpServletResponse response){
		String ids = request.getParameter("ids");
		for(String id : ids.split(",")){
			try {
				User user = this.userService.findUserById(Long.parseLong(id));
				user.setIsDelete("1");
				this.userService.updateUser(user);
			} catch (NumberFormatException e) {
				e.printStackTrace();
				return "0";
			} catch (DataException e) {
				e.printStackTrace();
				return "0";
			}
		}
		return "1";
	}
	
	/**
	 * 重置密码操作
	 * @return
	 */
	@RequestMapping("/resetPassword.do")
	@ResponseBody
	public String resetPassword(HttpServletRequest request,HttpServletResponse response){
		long id = Long.parseLong(request.getParameter("id").trim());
		
		boolean result = false;
		try {
			result = this.userService.resetPassword(id);
		} catch (DataException e) {
			e.printStackTrace();
		}
		return result?"1":"0";
	}
	
	
	/**
	 * 处理修改绑定手机号码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/jBoxUpdateUserMobile.do")
	@ResponseBody
	public String jBoxUpdateUserMobile(HttpServletRequest request,HttpServletResponse response){
		String mobile = request.getParameter("mobile");                            //接受客户端传递的新电话号码
		Long userId = Long.parseLong(request.getParameter("userId"));              //接受客户端传递过来的id
		try {
			@SuppressWarnings("unused")
			User user = userService.updateUserMobile(userId, mobile);
			return "1";    //成功返回1
		} catch (DataException e) {
			e.printStackTrace();
			return "0";
		}
	}
	
}
